<template>
  <div class="sign-wrapper">
    <div id='topScreen'>
      <div>成功 <br>
      请点击签名更新按钮</div>
      
    </div>
    <div class="canvas-box" id="canvasBig" :style="getHorizontalStyle">
    <canvas></canvas>
    <!-- 画布操作按钮 -->
    <div class="btn_box">
      <!-- <span class="btn last-btn" @touchstart.stop="lastPNG">使用上次签名
      </span> -->
      <!-- <el-checkbox class='last-btn' v-model="checked">该签名保存以备下次使用</el-checkbox> -->
      <span class="btn clear-btn" @touchstart.stop="clear">清空
      </span>
      <span class="btn commit-btn" @touchstart.stop="submitPNG">提交
      </span>
    </div>
    </div>
  </div>
</template>
<script>
import Draw from "@/utils/draw"; 
import { SetImgFiles } from '../../api/requestForm.js'

export default {
  name: '',
  components: {
  },
  data() {
    return {
      viewScanCodeUrl: '',  // 签名地址
      randomNum: '',      //随机字符串
      degree: 90,           //旋转度数
      checked: false,
    }
  },
  mounted() {
    console.log('========进入挂载==== mounted')
    this.canvasBox = document.getElementById('canvasBig');
    this.initCanvas();
  },
  computed: {
    //计算画布大小
    getHorizontalStyle() {
      const d = document;
      const w = window.innerWidth || d.documentElement.clientWidth || d.body.clientWidth;
      const h = window.innerHeight || d.documentElement.clientHeight || d.body.clientHeight;
      let length = (h - w) / 2;
      let width = w;
      let height = h;

      switch (this.degree) {
        case -90:
          length = -length;
        case 90:
          width = h;
          height = w;
          break;
        default:
          length = 0;
      }

      if (this.canvasBox) {
        this.canvasBox.removeChild(document.querySelector('canvas'));
        this.canvasBox.appendChild(document.createElement('canvas'));
        console.log('this.canvasBox333333:',this.canvasBox)
        setTimeout(() => {
          this.initCanvas();
        }, 200);
      }
      return {
        transform: `rotate(${this.degree}deg) translate(${length}px,${length}px)`,
        width: `${width}px`,
        height: `${height}px`,
        transformOrigin: 'center center',
      };
    },
  },
    methods: {
    //初始化签名画布
    initCanvas() {
      console.log(123, document.querySelector('canvas'))
      let canvas = document.querySelector('canvas');
      this.draw = new Draw(canvas, -this.degree);
      console.log('初始化画布11111canvas-------',canvas)
      console.log('this.draw111111111',this.draw)
    },
    //下载图片
    download() {
     this.draw.downloadPNGImage(this.draw.getPNGImage());
    },
    // 获取上次签名
    lastPNG() {},
    //清空画布
    clear() {
      console.log('clear')
      this.draw.clear();
    },
    //上传签名
    async submitPNG() {
      // this.$store.dispatch('changeSgin2', 123)
      // console.log(this.$store, 'state')
      // return
      console.log('点击进行提交1111：',this.draw.isDraw);
      if (!this.draw.isDraw) {
        this.$message({
          message: '请先进行签署'
        })
        return
      }
      this.signImage = this.draw.getPNGImage();
      console.log('this.signImage', this.signImage);

      // 返回blob文件对象
      const dataURLtoFile = (dataurl, filename) => {
        const arr = dataurl.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      };
      
      const filename = `${new Date().getTime()}img.png`;
      const imgfile = dataURLtoFile(this.signImage, filename);
      console.log(imgfile, 'imgfile')
      let formData = new FormData();
      formData.set('file', imgfile)
      const that = this
      SetImgFiles(formData, that.randomNum).then((res) => {
        console.log('submit', res)
        if(res.data.url) {
          // 跳转页面/弹窗全部遮盖不关闭 提示web点击获取签名
         document.getElementById("topScreen").style.display = "flex";
         // 图片获得地址后如何传给另一个页面? 让他获取 --> 保存至本地
        // localStorage.setItem('newSign', res.data.url)
        }
      })
      if(this.checked) {
        // 保留缓存
      }
    },
  },
  created() {
    this.randomNum = this.$route.query.id
    console.log('this.$route.query.id',this.$route.query.id)
    //console.log('进入签名created=====横屏竖屏',window.orientation,this.orderListId)
    //判断手机横竖屏状态：   
    // window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {   
    //  if (window.orientation === 180 || window.orientation === 0) {    
    //     console.log('竖屏状态！')
    //  }    
    //   if (window.orientation === 90 || window.orientation === -90 ){    
    //     console.log('横屏状态！')
    //   }     
    // }, false);  
  }
}
</script>

<style lang="less" scoped>
.sign-wrapper {
  height: 100%;
  width: 100%;
  background: #fff;
  //手写签名 canvas
  .canvas-box {
    height: 100%;
    display: flex;
  }
}
canvas {
  flex: 1;
  // cursor: crosshair;
}
// 操作按钮
.btn {
  width: 6.8rem;
  height: 3.5rem;
  position: absolute;
  right: 2rem;
  bottom: 0.5rem;
  display: inline-block;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: .25rem;
  color: #fff;
  font: 1.6rem '苹方-简';
  z-index: 2;
  border: none
}
.clear-btn {
  background: #999999;
  right: 9.5rem;
}
.commit-btn {
  background: #3978E1
} 
.last-btn {
  width: 12rem;
  right: 17rem;
  bottom: 0.5rem;
  position: absolute;
  font: 1.6rem '苹方-简';
  z-index: 2;
  color: #409EFF;
}
#topScreen {
  width: 100%;
  height: 100%;
  background-color: rgb(110, 231, 146);
  // margin: -10px;
  color: #fff;
  font-size: 1.6rem;;
  position: absolute;
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 5;
  text-align: center;
 line-height: 3rem;;
}
#topScreen div{
  transform: rotate(90deg);
}
</style>
<style scoped>
.sign-wrapper {
  orientation-lock: portrait;
  touch-action: none; /* for modern browsers */
  -webkit-touch-callout: none; /* for iOS Safari */
}
</style>